package com.rtx.wms.std.handler.transfer.upload;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.wms.customer.common.upload.UploadService;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.transer.bean.ApiTransferFinish;
import com.rtx.wms.std.transer.service.ApiTransferFinishService;

import cn.hutool.core.util.StrUtil;

@Component
public class TransferReturnHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ApiTransferFinishService apiTransferFinishService;
    
    @Autowired
    ApplicationContext applicationContext;

    /**
     * 处理完成的出库单
     * @param whseid
     */
    public void handlerOrdersUpload(String whseid,ApiMappingInfoBo bo){
        //获取待回传的出库单
        List<ApiTransferFinish> list = selectfinish("ris_edi");
        for(ApiTransferFinish o : list){
            //回传
        	UploadService service =(UploadService)applicationContext.getBean(bo.getApimappingcode());
        	service.uploadHandle(o);
            //更新状态
            updateStatus(whseid,o);
        }
    }

    /**
     * 更新出库单
     * @param whseid
     * @param o
     */
    private void updateStatus(String whseid, ApiTransferFinish o) {
        LambdaUpdateWrapper<ApiTransferFinish> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(ApiTransferFinish::getTransferkey,o.getTransferkey())
                .set(ApiTransferFinish::getEdiflag,o.getEdiflag())
                .set(ApiTransferFinish::getEdimsg, StrUtil.sub(o.getEdimsg(),0,499));
        apiTransferFinishService.updStatus(whseid,wrapper);
    }

    /**
     * 查询需要回传上位出库单
     * @param whseid
     * @return
     */
    public List<ApiTransferFinish> selectfinish(String whseid){
    	LambdaUpdateWrapper<ApiTransferFinish> qw = Wrappers.lambdaUpdate();
    	qw.eq(ApiTransferFinish::getEdiflag, WmsConstant.DEFAULT_FLAG);
    	qw.eq(ApiTransferFinish::getToexamine, "0");
    	qw.lt(ApiTransferFinish::getRtxqueue, WmsConstant.DEFAULT_COUNT);
        return apiTransferFinishService.queryWithDetailByCondition(whseid, null);
    }
}
